//
// Created by lfm on 2025/3/16.
//

#include "Management.h"
#include "Student.h"
#include <fstream>
#include <iostream>
#include <memory>
using namespace std;

// 管理类，负责学生信息的管理操作
Management::Management()
{
    if (!readFile("student.txt"))
    {
        // 可以选择进行其他处理，如提示用户创建文件等
        cout << "Failed to read file. System will continue with empty data."
             << endl;
    }
}

// 显示学生管理系统的菜单选项
void Management::menu()
{
    cout << "***** 学生管理系统 *****" << endl;
    cout << "**** 1.查看学生信息 ****" << endl;
    cout << "**** 2.添加学生信息 ****" << endl;
    cout << "**** 3.删除学生信息 ****" << endl;
    cout << "**** 4.修改学生信息 ****" << endl;
    cout << "**** 5.查找学生信息 ****" << endl;
    cout << "**** 6.排序学生信息 ****" << endl;
    cout << "**** 7.退出系统     ****" << endl;
    cout << "**** 0.清屏：       ****" << endl;
    cout << endl;
}

// 运行学生管理系统的主循环，根据用户选择执行不同的操作
bool Management::Run()
{
    this->menu();
    static int select = 0;
    cout << "select>";
    cin >> select;
    switch (select)
    {
    case Management::Clear:
        system("cls");
        break;
    case Management::Show:
        this->show();
        break;
    case Management::Insert:
        this->insert();
        break;
    case Management::Remove:
        this->remove();
        break;
    case Management::Modify:
        this->modify();
        break;
    case Management::Search:
        this->search();
        break;
    case Management::Sort:
        this->sort();
        break;
    case Management::Exit:
        writeFile("student.txt");
        exit(0);
        break;
    }
    return true;
}

// 从指定文件读取学生信息
bool Management::readFile(const std::string &fileName)
{
    fstream read(fileName, ios::in);
    if (!read.is_open())
    {
        cout << fileName << " open failed!" << endl;
        return false;
    }
    // 读取表头
    char buf[BUFSIZ] = {0};
    read.getline(buf, BUFSIZ);
    tableHeader = buf;

    std::string id, name;
    int age, chinese, math, english;
    while (read >> id >> name >> age >> chinese >> math >> english)
    {
        Student *stu = new Student(name, id, age, chinese, math, english);
        stu_vec.push_back(stu);
    }

    read.close();
    return true;
}

// 将学生信息写入指定文件
void Management::writeFile(const std::string &fileName)
{
    fstream write(fileName, ios::out | ios::trunc);
    if (!write.is_open())
    {
        cerr << fileName << "open failed!" << endl;
        return;
    }
    // 写入表头
    write << tableHeader << "\n";
    for (auto &stu : stu_vec)
    {
        write << *stu;
    }
    write.close();
}

// 显示所有学生的信息
void Management::show()
{
    cout << tableHeader << endl;
    for (auto &stu : stu_vec)
    {
        cout << stu->m_Id << "\t" << stu->m_Name << "\t" << stu->m_Age << "\t"
             << stu->m_Chinese << "\t" << stu->m_Math << "\t" << stu->m_English
             << endl;
    }
    cout << "\n" << "总共有[" << stu_vec.size() << "]条记录" << endl;
}

// 添加新的学生信息
void Management::insert()
{
    std::string id, name;
    int age, chinese, math, english;
    cout << "请依次输入学号，姓名，年龄，语文，数学，英语：" << endl;
    cin >> id >> name >> age >> chinese >> math >> english;
    Student *stu = new Student(name, id, age, chinese, math, english);
    stu_vec.push_back(stu);
}

// 根据学号删除学生信息
void Management::remove()
{
    string id;
    cout << "请输入要删除的学生学号：" << endl;
    cin >> id;
    // 查找有没有学号为id的学生
    auto delIt = std::find_if(stu_vec.begin(), stu_vec.end(),
                              [id](Student *stu) { return stu->m_Id == id; });
    if (delIt != stu_vec.end())
    {
        delete *delIt; // 释放内存
        stu_vec.erase(delIt);
        cout << "remove success!" << endl;
    }
    else
    {
        cout << "Student not found!" << endl;
    }
}

// 根据学号修改学生信息
void Management::modify()
{
    cout << "请输入你要修改的学生学号" << endl;
    string id;
    cin >> id;
    auto it = std::find_if(stu_vec.begin(), stu_vec.end(),
                           [id](Student *stu) { return stu->m_Id == id; });
    if (it != stu_vec.end())
    {
        cout << "请输入修改后的学生信息：" << endl;
        string newName, newId;
        int newAge, newChinese, newMath, newEnglish;
        cin >> newId >> newName >> newAge >> newChinese >> newMath >>
            newEnglish;
        (*it)->m_Id = newId;
        (*it)->m_Name = newName;
        (*it)->m_Age = newAge;
        (*it)->m_Chinese = newChinese;
        (*it)->m_Math = newMath;
        (*it)->m_English = newEnglish;
        cout << " 修改成功!" << endl;
    }
    else
    {
        cout << "找不到该学生！" << endl;
    }
}

// 根据学号查找学生信息
void Management::search()
{
    cout << "请输入你要查找的学生的学号" << endl;
    string idSearch;
    cin >> idSearch;
    auto id =
        std::find_if(stu_vec.begin(), stu_vec.end(), [idSearch](Student *stu)
                     { return stu->m_Id == idSearch; });
    if (id != stu_vec.end())
    {
        cout << "找到了该学生！" << endl;
        cout << "学号:" << (*id)->m_Id << "\t" << "姓名:" << (*id)->m_Name
             << "\t" << "年龄:" << (*id)->m_Age << "\t"
             << "语文:" << (*id)->m_Chinese << "\t" << "数学:" << (*id)->m_Math
             << "\t" << "英语:" << (*id)->m_English << endl;
    }
    else
    {
        cout << "没有通过学号找到该学生！" << endl;
    }
}

// 对学生信息进行排序
void Management::sort()
{
    // 按照语文分数排序
    // 如果要修改排序的依据和规则，可以修改lambda表达式
    // 假如要按照年龄排序，可以修改为：
    // std::sort(stu_vec.begin(), stu_vec.end(), [](Student* a, Student* b)
    //{
    //     return a->m_Age < b->m_Age;
    // });
    std::sort(stu_vec.begin(), stu_vec.end(), [](Student *a, Student *b)
              { return a->m_Chinese > b->m_Chinese; });
    cout << "排序成功！" << endl;
}

// 添加析构函数，释放所有分配的内存
Management::~Management()
{
    for (auto &stu : stu_vec)
    {
        delete stu;
    }
    stu_vec.clear();
}